package com.yk.filedownload.downloader.DownloadCell.impl;

import com.yk.filedownload.ConfigIt.Configuration;
import com.yk.filedownload.DataTransfer.RedisOp.RedisOperation;
import com.yk.filedownload.DataTransfer.RedisOp.impl.RedisOperationImpl;
import com.yk.filedownload.downloader.DownloadCell.CommonCell;
import com.yk.filedownload.entity.DataCarrier;
import com.yk.filedownload.util.logger.ExceptionCatcher;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Project Name:cykfiledownload
 * File Name:SingleThreadCell
 * Package Name:com.yk.filedownload.service
 * Date:2017\12\6 0006
 * Author:dengtianjia
 * Description:
 * Copyright (c) 2017, 重庆云凯科技有限公司 All Rights Reserved.
 */
public class SingleThreadCell  extends CommonCell {

    private Logger logger = Logger.getLogger(SingleThreadCell.class);

    private byte[] mateData = null;

    private String uuid;

    private HttpURLConnection conn;

    private DataCarrier carrier = new DataCarrier();

    private RedisOperation redisOperation;

    private Integer RealTimeSize = 0 ;

    private Long startTime ;

    private Integer packSize;

    private Double rate = 30.0;

    private ExceptionCatcher catcher = new ExceptionCatcher();

    public SingleThreadCell(String uuid ,HttpURLConnection conn , Integer packSize) {
        this.uuid = uuid;
        this.conn = conn;
        this.packSize = packSize;
        redisOperation = new RedisOperationImpl();

    }


    @Override
    public void run() {
        try {
            System.out.println("进入单文件下载");

            startTime = System.currentTimeMillis();

            Long endTime ;

            InputStream in = conn.getInputStream();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int rc = 0;
            while ((rc = in.read(buff, 0, 1024)) > 0) {
                swapStream.write(buff, 0, rc);
                RealTimeSize++;
                /**
                 * 检测平均下载速率代码块
                 */
                Long costTime_now =  System.currentTimeMillis() - startTime;
                if((packSize.doubleValue()/1024.0)/(costTime_now.doubleValue()/1000) < Configuration.MIN_DOWNLOAD_RATE_OF_THREAD){
                    super.BackThrLowRateUrl(conn.getURL().toString());
                    return;
                }
            }
            mateData = swapStream.toByteArray();
            swapStream.close();
            in.close();
            conn.disconnect();

            carrier.setFileId(uuid);
            carrier.CompressData(mateData);
            /**
             * 测试代码块
             */
            File file = new File("H:/test/file/"+uuid+".temp");
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(carrier.getCompressData());
            /**
             * 将文件写入redis中
             */
//          super.dataWriteIntoRedis(carrier,RealTimeSize);
        }catch (Exception e){
            catcher.catchException(e,logger,this);
        }
    }

    @Override
    public Map getSatus() {
        rate = super.getDownLoadRate(RealTimeSize,startTime);
        Map status = new HashMap();
        status.put("Thread_ID" , uuid);
        status.put("Thread_URL",conn.getURL().toString());
        status.put("Thread_Rate",rate);
        status.put("Thread_NUM",1);
        return status;
    }
}
